<?php
require_once("page.class.php");
require_once("functions.php");
require_once("rokovnik.class.php");
require_once("porezi.class.php");
require_once("adrese.class.php");

define("PAGE_LENGTH",50);

class ugovori extends page{
	var $db;
	var $adrese;
	var $tbl_ulaz = "ugovori_ulaz";
	var $tbl_izdaj = "ugovori_izdavanje";
	
	var $lok_types = array(
		1	=> "grad",
		2	=> "lok.opština",
		3	=> "naselje"
	);
	
	var $logoDirectory="logo/";
	var $banerDirectory="baner/";
	
	function ugovori($get){
		if(!$this->isUserLoggedIn()){
			header("Location: index.php");
		}
		$this->loadConfig();
		
		$this->db = new db_functions();
		$this->adrese = new adrese();
		$mod = getFromInput("mod");
		$a = getFromInput("a");
		//echo "$a<br />$mod";
		switch($a){
			case "admin":
				switch ($mod){
					case "dopistype":
						$this->adminDopisTypes();
						break;
					case "dopistypesave":
						$this->saveDopisType();
						break;
					case "dopistypedelete":
						$this->deleteDopisType();
						break;
					case "dopisishod":
						$this->adminDopisIshod();
						break;
					case "dopisishodsave":
						$this->saveDopisIshod();
						break;
					case "dopisishoddelete":
						$this->deleteDopisIshod();
						break;
				}
				break;
			case "alarms":
				$this->alarms();
				break;
			case "checkLogo":
				$this->CheckLogo();
				break;
			case 'fakture':
				require_once("classes/ugovori.fakture.class.php");
				$fak = new ugovori_fakture();
				switch ($mod){
					case "afterSaveImport":
						$fak->displayImportedFile();
						break;
					case "import":
						$fak->import();
						break;
					default:
						break;
				}
				break;
			case 'izdaj':
				$this->issueContractDisplay();
				break;
			case 'getCenovnikStavke':
				//$this->ugovorStavke();
				echo $this->getCenovnik(date2int(getFromInput("date")));
				break;
			case 'ugovorKomitentDetails':
				$this->ugovorKomitentDetails();
				break;
			case "ugovorKomitentZR":
				$this->ugovorKomitentZR();
				break;
			case 'new':
				$this->novi();
				break;
			case "save":
				$this->save();
				break;
			case "delete":
				$this->deleteUgovor();
				break;
			case 'deklaracija':
				switch ($mod){
					case "importKomitentData":
						$this->importDeklaracijaKomitentData();
						break;
					default:
						die("unknown");
						break;
				}
				break;
			case 'materijal':
				switch ($mod){
					case "new":
						$this->newUgovorAddMaterijal();
						break;
					case "edit":
						$this->newUgovorEditMaterijal();
						break;
				}
				break;
			case 'tokActions':
				switch ($mod){
					case "new":
						$this->newUgovorAddAction();
						break;
					case "edit":
						$this->newUgovorEditAction();
						break;
				}
				break;
			case 'plan':
				switch ($mod){
					case "makeTable":
						$this->planMakeTable();
						break;
				}
				break;
			case 'pregled':
				$this->browse();
				break;
			case 'display':
				$this->display();
				break;
			case 'check':
				$br = $get["br_ugo"];
				if(preg_match('/-/',$br)){
					$tmp = explode("-",$br,2);
					for($i=$tmp[0]; $i<=$tmp[1]; $i++){
						echo $i.",";
						if($this->isIssued($i)){
							echo '1';
						}else{
							echo NULL;
						}
						if($i<$tmp[1]){
							echo ";";
						}
					}
				}else{
					echo $br.",";
					if($this->isIssued($br)){
						echo '1';
					}else{
						echo NULL;
					}
				}
				break;
			case 'izdajDB':
				$br_ugo = $get["br_ugo"];
				$kol_pr = trim($get["kol_pr"])?trim($get["kol_pr"]):0;
				$radnik_id = $get["rad_id"];
				$komentar = trim($get["komentar"]);
				$this->addIssue($br_ugo,$kol_pr,$radnik_id,$komentar);
				break;
			case 'ulaz':
				$this->contractEntraceDisplay();
				break;
			case 'ulazDB':
				$this->addContract($get["params"]);
				break;
			case 'ulaz_mat':
				echo $this->parseTemplate("ugovori/ulaz_mat.tpl");
				break;
			case 'ulaz_mat_search':
				$ugo = $get["ugo"];
				$kom = $get["kom"];
				$this->searchUlazMat($ugo,$kom);
				break;
			case 'ulaz_mat_edit':
				$this->ulazMatEdit($get["id"],$get["kom"]);
				break;
			case 'ulaz_mat_save':
				$this->ulazMatSave($get["id"],$get["t"],$get["p"],$get["n"],$get["upd"]);
				break;
			case 'vracanje':
				switch ($mod){
					case 'vrati':
						$this->vratiUgovor();
						break;
					case 'unesi':
						$this->vratiUnesiUgovor();
						break;
					case 'showVrati':
						$this->showVratiUgovor();
						break;
				}
				break;
			case "razduzi":
				switch ($mod){
					case "searchIzd":
						$this->searchIzdUgovor();
						break;
					case "razduzi":
						$this->razduzi();
						break;
					default:
						$this->razduzivanje();
				}
				break;
			case 'real_report':
				require_once("ugovori.reports.real.class.php");
				$rep = new ugovori_report();
				break;
			case 'report':
				require_once("ugovori.reports.class.php");
				$params = array();
				$type = trim($get["t"]);
				$params["start"] = trim($get["start"]);
				$params["end"] = trim($get["end"]);
				$params["start_ugo"] = trim($get["start_ugo"]);
				$params["end_ugo"] = trim($get["end_ugo"]);
				$params["br_ug"] = trim($get["bu"]);
				$params["rad"] = trim($get["rad"]);
				$params["kom"] = trim($get["kom"]);
				$params["mat"] = trim($get["mat"]);
				$params["stor"] = trim($get["stor"]);
				$params["potpun"] = trim($get["potpun"]);
				$params["tip"] = trim($get["tip"]);
				$params["komentar"] = trim($get["komentar"]);
				$rep = new ugo_report();
				
				$page = (isset($get["page"]) && $get["page"]>0)?$get["page"]:1;
				
				$rep->showReport($type,$params,$page);
				break;
			case 'delitem':
				$id = $get["id"];
				$ok = true;
				
				if(!$this->db->alterTable("DELETE FROM ugovori_ulaz WHERE id=$id")){
					$ok = false;
				}else{
					if(!$this->db->alterTable("DELETE FROM ugovori_ulaz_materijal WHERE id=$id")){
						$ok = false;
					}elseif (!$this->db->alterTable("DELETE FROM ugovori_ulaz_vracen WHERE ulaz_id=$id")){
						$ok = false;
					}
				}
				
				if($ok){
					echo "Ulaz uspešno obrisan!";
				}else{
					echo "Ulaz nije obrisan!";
				}
				break;
		}
	}	
	function razduzivanje(){
		$polja = rokovnik::get_Radnici();
		//print_rarray($polja);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
		
		echo $this->parseTemplate("ugovori/razduzivanje.tpl");
	}
	function searchIzdUgovor(){
		$brugo = getFromInput("brugo");
		$this->assign("search_kword",$brugo);
		
		$q = "SELECT ui.*, r.radnik_ime, r.radnik_prezime "
			."FROM ugovori_izdavanje ui, radnici r "
			."WHERE br_ugovora LIKE '%$brugo%' "
			."AND r.radnik_id=ui.radnik "
			."ORDER BY ui.datum DESC";
		$res = $this->db->select2($q);
		
		if($res !== false){
			
			$this->assign("search_length",count($res));
			
			foreach ($res as $k=>$row){
				$ids[] = $k+1;
				$date = date($this->getFromConfig("short_date"),$row["datum"]);
				//$date = $row["datum"];
				$radnik = $row["radnik_ime"]." ".$row["radnik_prezime"];
				
				$br_ugo1 = str_replace($brugo,'<span style="text-decoration:underline">'.$brugo.'</span>',$row["br_ugovora"]);
				
				$items[] = "<strong>$br_ugo1</strong> - $date, $radnik";
				
				$onclick[] = 'setIzdatUgovor('.$row["id"].',\''.$row["br_ugovora"].'\',\''.$date.'\',\''.$radnik.'\');closeYpAjaxForm();';
			}

			$this->assign("list_num",$ids);
			$this->assign("list_item",$items);
			$this->assign("onclick",$onclick);
		}else{
			$this->assign("search_length","0");
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		
		echo $this->parseTemplate("search_list.tpl");
	}	
	function razduzi(){
		$izd_id = getFromInput("izd_id");
		$radnik = getFromInput("radnik");
		$datum = time();
		
		$q = "SELECT id FROM ugovori_razduzivanje WHERE izdavanje_id=$izd_id AND radnik=$radnik";
		$izdat = $this->db->getOne($q);
		if($izdat>0){
			die("Ugovor je već razdužen.");
		}
		
		$q = "SELECT uu.br_ugovora "
			."FROM ugovori_ulaz uu, ugovori_izdavanje ui "
			."WHERE uu.br_ugovora=ui.br_ugovora "
			."AND ui.id=$izd_id";
		$res = $this->db->getRow($q);
		if($res!==null){
			die("Ugovor ".$res[0]." je već ušao u firmu.");
		}
		
		$q = "INSERT INTO ugovori_razduzivanje VALUES('',$izd_id,$datum,$radnik)";
		if($this->db->alterTable($q)){
			echo "Ugovor je razdužen.";
		}else{
			echo mysql_error();
		}
	}	
	function _get($q){
		$res = $this->db->select2($q);
		return $res;
	}
	function issueContractDisplay(){
		$d = date("d.m.Y H:i:s");
		$workers = $this->_get("SELECT radnik_id,radnik_ime,radnik_prezime FROM radnici WHERE radnik_akt=1 ORDER BY radnik_ime");
		foreach($workers as $v){
			$rad_ids[] = $v["radnik_id"];
			$rad_names[] = $v["radnik_ime"];
			$rad_surs[] = $v["radnik_prezime"];
		}
		$this->assign("datum",$d);
		$this->assign("radnik_id",$rad_ids);
		$this->assign("radnik_ime",$rad_names);
		$this->assign("radnik_prezime",$rad_surs);
		echo $this->parseTemplate("ugovori/izdavanje.tpl");
	}
	function addIssue($br_ugo,$kol_pr,$radnik_id,$komentar){
		$tmp = explode("-",$br_ugo);
		foreach ($tmp as $k=>$v){
			$tmp[$k] = intval($v);
		}
		
		$log = $_COOKIE["ypu"]."#".$_SERVER['REMOTE_ADDR']."#".time();
		if(count($tmp)==1){
			$q = "SELECT id FROM ugovori_izdavanje WHERE br_ugovora='".$br_ugo."'";
			$res = $this->db->select1($q);
			if($res){
				foreach($res as $v){
					$q = "UPDATE ugovori_izdavanje SET storno=1 WHERE id=".$v[0];
					$this->db->alterTable($q);
				}
			}
			$d = time();
			$q = "INSERT INTO ".$this->tbl_izdaj."(datum,br_ugovora,kol_predracuna,radnik,komentar,log) "
				."VALUES (".$d.",'".sprintf("%'05d",$br_ugo)."',".$kol_pr.",".$radnik_id.",'".$komentar."','$log')";
			$r = @$this->db->alterTable($q);
			if($r){
				echo "Ugovor #".sprintf("%'05d",$br_ugo)." uspešno izdat.";
			}else{
				echo "Greška pri izdavanju ugovora!\n".mysql_error();
			}
		}else{
			$start = $tmp[0];
			$end = $tmp[1];
			if($start >= $end){
				echo "Izdavanje neuspelo.\nDrugi broj ugovora je manji ili jednak prvom broju.";
			}else{
				$ok = true;
				for($i = $start; $i <= $end; $i++){
					$q = "SELECT id FROM ugovori_izdavanje WHERE br_ugovora='".sprintf("%'05d",$i)."'";
					$res = $this->db->select1($q);
					if($res){
						foreach($res as $v){
							$q = "UPDATE ugovori_izdavanje SET storno=1 WHERE id=".$v[0];
							$this->db->alterTable($q);
						}
					}
					$d = time();
					if($i==$start){
						$kpr = $kol_pr;
					}else{
						$kpr = 0;
					}
					
					$q = "INSERT INTO ".$this->tbl_izdaj."(datum,br_ugovora,kol_predracuna,radnik,komentar,log) "
						."VALUES (".$d.",'".sprintf("%'05d",$i)."',".$kpr.",".$radnik_id.",'".$komentar."','$log')";
					$r = @$this->db->alterTable($q);
					if(!$r){
						$ok = false;
						break;
					}
				}
				if($ok){
					echo "Ugovori #".sprintf("%'05d",$start)." - ".sprintf("%'05d",$end)." uspešno izdati.";
				}else{
					echo "Greška pri izdavanju ugovora!\n".mysql_error();
				}
			}
		}
	}
	function isIssued($br_ugo){
		$q = "SELECT id FROM ugovori_izdavanje WHERE br_ugovora='".sprintf("%'05d",$br_ugo)."'";
		$res = $this->db->select1($q);
		if($res){
			return true;
		}else{
			return false;
		}
	}
	function contractEntraceDisplay(){
		$d = date("d.m.Y H:i:s");
		$workers = $this->_get("SELECT radnik_id,radnik_ime,radnik_prezime FROM radnici WHERE radnik_akt=1 ORDER BY radnik_ime");
		$kampanje = $this->_get("SELECT kampanja_id,kampanja_naziv FROM kampanje ORDER BY kampanja_start_date DESC");
		$art_grupe = $this->_get("SELECT artgr_id,artgr_name FROM artikli_grupe WHERE artgr_id>0 ORDER BY artgr_name");
		$artikli = $this->_get("SELECT art_id,art_name,art_desc FROM artikli ORDER BY art_name");
		$art_tipovi = $this->_get("SELECT arttip_id,arttip_name FROM artikli_tipovi ORDER BY arttip_name");
		$art_boje = $this->_get("SELECT art_boja_id,art_boja_name,art_boja_code FROM artikli_boje ORDER BY art_boja_code");
		$jmere = $this->_get("SELECT unit_id,unit_value,unit_svalue FROM jedinice_mere ORDER BY unit_value");
		
		foreach($workers as $v){
			$rad_ids[] = $v["radnik_id"];
			$rad_names[] = $v["radnik_ime"];
			$rad_surs[] = $v["radnik_prezime"];
		}
		foreach($kampanje as $v){
			$kampanja_ids[]=$v["kampanja_id"];
			$kampanja_name[]=$v["kampanja_naziv"];
		}
		foreach($art_grupe as $v){
			$artgr_id[]=$v["artgr_id"];
			$artgr_name[] = $v["artgr_name"];
		}
		foreach($artikli as $v){
			$art_ids[]=$v["art_id"];
			$art_names[]=$v["art_name"];
			$art_descs[]=$v["art_desc"];
		}
		foreach($art_tipovi as $v){
			$arttip_ids[]=$v["arttip_id"];
			$arttip_names[]=$v["arttip_name"];
		}
		foreach($art_boje as $v){
			$art_boja_ids[] = $v["art_boja_id"];
			$art_boja_names[] = $v["art_boja_name"];
			$art_boja_codes[] = $v["art_boja_code"];
		}
		foreach($jmere as $v){
			$unit_ids[]=$v["unit_id"];
			$unit_values[]=$v["unit_value"];
			$unit_svalues[]=$v["unit_svalue"];
		}
		$this->assign("radnik_id",$rad_ids);
		$this->assign("radnik_ime",$rad_names);
		$this->assign("radnik_prezime",$rad_surs);
		$this->assign("kampanja_id",$kampanja_ids);
		$this->assign("kampanja_name",$kampanja_name);
		$this->assign("artgr_id",$artgr_id);
		$this->assign("artgr_name",$artgr_name);
		$this->assign("art_id",$art_ids);
		$this->assign("art_name",$art_names);
		$this->assign("art_desc",$art_descs);
		$this->assign("art_tip_id",$arttip_ids);
		$this->assign("art_tip_name",$arttip_names);
		$this->assign("art_boja_id",$art_boja_ids);
		$this->assign("art_boja_name",$art_boja_names);
		$this->assign("art_boja_code",$art_boja_codes);
		$this->assign("unit_id",$unit_ids);
		$this->assign("unit_value",$unit_values);
		$this->assign("unit_svalue",$unit_svalues);
		echo $this->parseTemplate("ugovori/ulaz.tpl");
	}
	function addContract($params){
		
		$dat_ulaza = time();
		$params = utf8RawUrlDecode($params);
		$params = utf8RawChrDecode($params);
		$temp = explode("{!!}",$params);
		$row = array();
		$artikli = array();
		foreach($temp as $v){
			if(preg_match('/{!}/',$v)){
				$tmp = explode("{!}",$v);
				$l="";
				foreach($tmp as $m){
					$t = explode("=",$m,2);
					$l.=";".$t[1];
				}
				array_push($artikli,substr($l,1));
			}else{
				$tmp = explode("=",$v,2);
				$row[$tmp[0]] = $tmp[1];
			}
		}
		$row["artikli"] = $artikli;
		
		//print_r($row);die();
		
		if(strlen($row["br_ugovora"])<7){
			$q = "SELECT id FROM ugovori_izdavanje WHERE br_ugovora='".$row["br_ugovora"]."'";
			$res1 = $this->db->select1($q);
			if(!$res1){
				die("Ugovor broj ".$row["br_ugovora"]." nije izdat!");
			}
		}
		
		$q = "SELECT id,datum_ulaza FROM ugovori_ulaz WHERE br_ugovora='".$row["br_ugovora"]."'";
		$res2 = $this->db->select1($q);
		if($res2){
			die("Ugovor broj ".$row["br_ugovora"]." je već ušao ".date("d.m.Y",$res2[0][1]));
		}
		
		$d = explode(".",$row["datum_ugovora"],3);
		$t = makeUnixTime(0,0,0,$d[1],$d[0],$d[2]);
		
		$log = $_COOKIE["ypu"]."#".$_SERVER['REMOTE_ADDR']."#".time();
		
		foreach($artikli as $k=>$v){
			$arts = explode(";",$v);
			$art_id=$arts[0];
			$art_type=$arts[1];
			$art_color=$arts[2];
			$art_unit=$arts[3];
			$art_price=$arts[4];
			$art_mat=$arts[5];
			$art_potpun = $arts[6];
			$art_kom=$arts[7];
			$q1 = "SELECT art_grupa_id FROM artikli WHERE art_id=".$art_id;
			$art_grupa = $this->db->getOne($q1);
			
			if($art_grupa == "2"){
				$kamp=0;
			}else{
				$kamp = $row["kampanja"];
			}
			
			$q = "INSERT INTO ".$this->tbl_ulaz."(datum_ulaza,br_ugovora,datum_ugovora,kol_predracuna,radnik,komitent,kampanja,artikl,iznos,materijal,komentar,storno,log) "
				."VALUES("
				.$dat_ulaza.",'".$row["br_ugovora"]."',".$t.",".$row["kol_predracuna"].",".$row["radnik"]
				.",'".addslashes($row["komitent"])."',".$kamp.",'".$art_id.";".$art_type.";".$art_color.";".$art_unit."','"
				.$art_price."',".$art_mat.",'".$art_kom."',".$row["storno"].",'$log')";
			//echo $q;
			if($this->db->alterTable($q)){
				$last = $this->db->getOne("SELECT LAST_INSERT_ID() FROM ".$this->tbl_ulaz);
				if($art_mat){
					$radnik = $_COOKIE["ypu"];
					$ip = $_SERVER['REMOTE_ADDR'];
					$q = "INSERT INTO ugovori_ulaz_materijal(id,datum,poreklo,potpun,radnik,ip) "
						."VALUES($last,$dat_ulaza,'ulaz',$art_potpun,$radnik,'$ip')";
					if(!$this->db->alterTable($q)){
						die("Fatal error!\n".mysql_error());
					}
				}
				
				if($row["vracen"] && $k==0){
					$q = "INSERT INTO ugovori_ulaz_vracen VALUES('',$last,".$row["vracen"].",$dat_ulaza,1,'".addslashes($row["vracenComment"])."')";
					if (!$this->db->alterTable($q)) {
						die(mysql_error());
					}
				}
				
				$q = "SELECT DISTINCT radnik, id FROM ugovori_izdavanje WHERE br_ugovora='".$row["br_ugovora"]."'";
				$res = $this->db->select2($q);
				if($res !== false){
					$the=false;
					foreach ($res as $id){
						if($id["radnik"] !== $row["radnik"]){
							$q = "INSERT INTO ugovori_razduzivanje VALUES('',".$id["id"].",$dat_ulaza,".$id["radnik"].")";
							if(!$this->db->alterTable($q)){
								die(mysql_error());
							}
						}else{
							$the = true;
						}
					}
				}
				if(!$the){
					$q = "INSERT INTO ugovori_izdavanje VALUES('',$dat_ulaza,'".$row["br_ugovora"]."',1,".$row["radnik"].",0,'zadužen prilikom ulaza ugovora','$log')";
					if(!$this->db->alterTable($q)){
						die(mysql_error());
					}
				}
			}else{
				die("Fatal error!\n".mysql_error());
			}
		}
		echo "Ugovor uspešno unešen.";
	}
	
	/**
	 * NOVI UGOVOR
	 *
	 */
	function novi(){
		
		$last = $this->db->getOne("SELECT broj FROM ugovori ORDER BY id DESC LIMIT 1");
		$last=intval($last);
		$brugo = $last+1;
		$last = sprintf("%'05d",$last);
		$brugo = sprintf("%'05d",$brugo);
		
		$this->assign("br_ugovora_last",$last);
		$this->assign("br_ugovora",$brugo);
		
		//delatnosti
		$polja = $this->get_Delatnosti();
			$this->assign("del_id",$polja["polje_id"]);
			$this->assign("del_name",$polja["polje_ime"]);
		
		// kampanje
		$polja = $this->get_Kampanje();
			$this->assign("kampanja_id",$polja["polje_id"]);
			$this->assign("kampanja_name",$polja["polje_ime"]);
			$this->assign("kampanja_start",$polja["polje_start"]);
			$this->assign("kampanja_end",$polja["polje_end"]);
			$this->assign("kampanja_selected",$polja["polje_selected"]);
		
		$polja = $this->get_UgovorTipovi(1);
			$this->assign("ugovor_tip_id",$polja["polje_id"]);
			$this->assign("ugovor_tip",$polja["polje_ime"]);
			$this->assign("ugovor_tip_selected",$polja["polje_selected"]);
		$polja = $this->get_UgovorProblemi();
			$this->assign("problem_id",$polja["polje_id"]);
			$this->assign("problem",$polja["polje_ime"]);
		$this->assign("lok_tip_id",array_keys($this->lok_types));
		$this->assign("lok_tip_name",array_values($this->lok_types));
		
		$this->assign("ugovor_lid","45");
		$polja = $this->get_Lokacije(1,45);
			$this->assign("lok_grad_id",$polja["polje_id"]);
			$this->assign("lok_grad_name",$polja["polje_ime"]);
			$this->assign("lok_grad_ptt",$polja["polje_ptt"]);
			$this->assign("lok_grad_selected",$polja["polje_selected"]);
		$polja = $this->get_Lokacije(2);
			$this->assign("lok_ops_id",$polja["polje_id"]);
			$this->assign("lok_ops_name",$polja["polje_ime"]);
			$this->assign("lok_ops_ptt",$polja["polje_ptt"]);
		$polja = $this->get_Lokacije(3);
			$this->assign("lok_nas_id",$polja["polje_id"]);
			$this->assign("lok_nas_name",$polja["polje_ime"]);
			$this->assign("lok_nas_ptt",$polja["polje_ptt"]);
		
		$polja = $this->get_Radnici(null,1);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
		$polja = $this->get_Porezi(3);
			$this->assign("porez_id",$polja["polje_id"]);
			$this->assign("porez_name",$polja["polje_ime"]);
			$this->assign("porez_perc",$polja["polje_perc"]);
			$this->assign("porez_selected",$polja["polje_selected"]);
		$polja = $this->get_StatusiIzrade();
			$this->assign("ugovor_izrada_status_id",$polja["polje_id"]);
			$this->assign("ugovor_izrada_status",$polja["polje_ime"]);
		$polja = $this->get_UgovorNaciniPlacanja();
				$this->assign("np_id",$polja["polje_id"]);
				$this->assign("np_name",$polja["polje_ime"]);
				$this->assign("np_code",$polja["polje_code"]);
		
		$this->assign("stavka_head_name","Naziv artikla");
		$this->assign("itdt_id","1");
		$this->assign("logo_pre",$this->logoDirectory);
		$this->assign("baner_pre",$this->banerDirectory);
		$this->assign("itdt_tok",$this->parseTemplate("ugovori/novi/stavka_tok_item.tpl"));
		
		// deklaracije
		$polja = $this->get_DeklaracijaTipPoruke();
			$this->assign("dmt_id",$polja["polje_id"]);
			$this->assign("dmt_name",$polja["polje_ime"]);
		$this->assign("deklaracija_template",$this->parseTemplate("ugovori/novi/deklaracija.tpl"));
		
		// dopisi
		$polja = $this->get_DopisTipovi();
			$this->assign("dt_id",$polja["polje_id"]);
			$this->assign("dt_name",$polja["polje_ime"]);
		$polja = $this->get_DopisIshodi();
			$this->assign("di_id",$polja["polje_id"]);
			$this->assign("di_name",$polja["polje_ime"]);
		$this->assign("dopis_template",$this->parseTemplate("ugovori/novi/dopis.tpl"));
		
		$this->assign("basic_data",$this->parseTemplate("ugovori/novi/basic_data.tpl"));
		$this->assign("payment",$this->parseTemplate("ugovori/novi/payment.tpl"));
		$this->assign("items",$this->parseTemplate("ugovori/novi/stavke.tpl"));
		
		echo $this->parseTemplate("ugovori/novi/new.tpl");
	}
	function ugovorKomitentDetails(){
		$komid = getFromInput("id");
		$this->assign("komid",$komid);
		
		$q  = "SELECT * FROM komitenti WHERE komitent_id=$komid LIMIT 1";
		$res = $this->db->select2($q);
		$res = $res[0];
		
		foreach ($res as $k=>$v){
			$$k = $v;
			$this->assign("$k",$v);
		}
		
		if(!preg_match('/^'.$komitent_name.'$/i',$komitent_name1)){
			$this->assign("komname",$komitent_name." [$komitent_name1]");
		}else{
			$this->assign("komname",$komitent_name);
		}
		$this->assign("komitent_dat_osn",date($this->getFromConfig("short_date"),$komitent_dat_osn));
		
		// VIEW_ STATUS
		$vs = $this->db->getOne("SELECT name FROM komitenti_view_status WHERE id=$komitent_view_status LIMIT 1");
		$this->assign("komitent_view_status",$vs);
		
		// TIP
		$tip = $this->db->getOne("SELECT kom_tip_name FROM komitenti_tipovi WHERE kom_tip_id=$komitent_tip_id LIMIT 1");
		$this->assign("komitent_tip",$tip);
		
		// STRUKTURA
		$strukt = $this->db->getOne("SELECT kom_strukt_name FROM komitenti_strukture WHERE kom_strukt_id=$komitent_str_id LIMIT 1");
		$this->assign("komitent_struktura",$strukt);
		
		// ADRESA
		$a = $this->adrese->getAll($komitent_adresa);
		$mesto = $a["lokacija"]["mesto"]["name"];
		$ptt = $a["lokacija"]["mesto"]["ptt"];
		if(isset($a["lokacija"]["opstina"])){
			$mesto .= " / ".$a["lokacija"]["opstina"]["name"];
			if(strlen($a["lokacija"]["opstina"]["ptt"]))
				$ptt = $a["lokacija"]["opstina"]["ptt"];
		}
		if(isset($a["lokacija"]["naselje"])){
			$mesto .= " / ".$a["lokacija"]["naselje"]["name"];
			if(strlen($a["lokacija"]["naselje"]["ptt"]))
				$ptt = $a["lokacija"]["naselje"]["ptt"];
		}
		$this->assign("komitent_adresa",$a["ulica"]." ".$a["broj"].", $ptt $mesto");
		
		// TEL-FAX
		$res = $this->db->select2("SELECT DISTINCT telefon,fax FROM komitenti_telefoni WHERE kom_id=$komid AND del_id=0 ORDER BY telefon");
		if ($res !== false) {
			foreach ($res as $row){
				if ($row["fax"]==0) {
					$tel[] = $row["telefon"];
				}else{
					$fax[] = $row["telefon"];
				}
			}
			$this->assign("komitent_telefon",@implode("<br />",$tel));
			$this->assign("komitent_fax",@implode("<br />",$fax));
		}
		// EMAIL
		$res = $this->db->select2("SELECT email FROM komitenti_emails WHERE kom_id=$komid AND del_id=0 ORDER BY email");
		if($res !== false){
			foreach ($res as $row){
				$email[] = $row["email"];
			}
			$this->assign("komitent_email",implode("<br />",$email));
		}
		// WEB
		$res = $this->db->select2("SELECT web FROM komitenti_webs WHERE kom_id=$komid AND del_id=0 ORDER BY web");
		if($res !== false){
			foreach ($res as $row){
				$web[] = $row["web"];
			}
			$this->assign("komitent_web",implode("<br />",$web));
		}
		
		// DELATNOSTI
		$res = $this->db->select2("SELECT DISTINCT delatnost_ime FROM komitenti_delatnosti kd, delatnosti d WHERE kd.komdel_kom_id=$komid AND kd.komdel_del_id=d.delatnost_id ORDER BY delatnost_ime");
		if ($res !== false) {
			foreach ($res as $row){
				$del[] = $row["delatnost_ime"];
			}
			$this->assign("komitent_delatnosti", implode(", ",$del));
		}
		
		// ZR
		$res = $this->db->select2("SELECT banka_name, ziro_value FROM komitenti_ziro_racuni kzr, banke b WHERE kzr.ziro_banka_id=b.banka_id AND kzr.ziro_komitent_id=$komid ORDER BY banka_name, ziro_value");
		if($res !== false){
			foreach ($res as $row){
				$zr[] = $row["banka_name"].": ".$row["ziro_value"];
			}
			$this->assign("komitent_ziro",implode("<br />",$zr));
		}
		
		echo $this->parseTemplate("ugovori/ugovor_komitent_details.tpl");
	}
	function ugovorKomitentZR(){
		$komid = getFromInput("kom");
		$zr = readValFromInput("zr");
		$banka = getFromInput("banka");
		
		$banke = $this->db->select1("SELECT banka_id, banka_name FROM banke ORDER BY banka_name");
		if ($banke !== false) {
			$banke_options="";
			foreach ($banke as $b){
				$banke_options .= '<option value="'.$b[0].'"';
				if ($b[0]==$banka) {
					$banke_options .= " selected";
				}
				$banke_options .= '>'.$b[1].'</option>';
			}
			$this->assign("banke_options",$banke_options);
		}
		$this->assign("ugovor_komitent_zr",$zr);
		$q = "SELECT ziro_value, ziro_banka_id, banka_name FROM banke b, komitenti_ziro_racuni kzr WHERE b.banka_id=kzr.ziro_banka_id AND kzr.ziro_komitent_id=$komid";
		$res = $this->db->select2($q);
		if ($res !== false) {
			$ima=false;
			foreach ($res as $k=>$row){
				$zrs["zr"][$k] = $row["ziro_value"];
				$zrs["banka"][$k] = $row["banka_name"];
				$zrs["banka_id"][$k] = $row["ziro_banka_id"];
				
				if ($row["ziro_value"]==$zr && $row["ziro_banka_id"]==$banka) {
					$zrs["zr_selected"][$k] = " selected";
					$ima=true;
				}else{
					$zrs["zr_selected"][$k] = "";
				}
			}
			if ($ima) {
				$this->assign("display_new_zr","none");
			}else{
				$this->assign("display_new_zr","block");
			}
			
			$this->assign("zr",$zrs["zr"]);
			$this->assign("banka_id",$zrs["banka_id"]);
			$this->assign("banka_name",$zrs["banka"]);
			$this->assign("zr_selected",$zrs["zr_selected"]);
		}
		
		echo $this->parseTemplate("ugovori/ugovor_komitent_zr.tpl");
	}
	function ugovorStavke(){
		$date = getFromInput("date");
		$time = date2int($date);
		
		$this->assign("logo_pre",$this->logoDirectory);
		$this->assign("baner_pre",$this->banerDirectory);
		
		list($cenovnik_id,$cenovnik_date) = $this->db->getRow("SELECT cenovnik_id, cenovnik_start FROM cenovnici WHERE cenovnik_start<$time ORDER BY cenovnik_start DESC LIMIT 1");
		if($cenovnik_id>0){
			
			echo date($this->getFromConfig("short_date"),$cenovnik_date)."{!}";
			echo "$cenovnik_id{!}";
			
			$polja = $this->get_Delatnosti();
				$this->assign("del_id",$polja["polje_id"]);
				$this->assign("del_name",$polja["polje_ime"]);
			
			$polja = $this->get_Kampanje();
				$now = time();
				foreach ($polja["polje_start"] as $k=>$v){
					
					if($polja["polje_start"][$k]<$now && $polja["polje_end"][$k]>$now){
						$polja["polje_selected"][$k] = " selected";
					}else{
						$polja["polje_selected"][$k] = "";
					}
					
					$polja["polje_start"][$k] = date("d.m.Y",$v);
					$polja["polje_end"][$k] = date("d.m.Y",$polja["polje_end"][$k]);
				}
				$this->assign("kampanja_id",$polja["polje_id"]);
				$this->assign("kampanja_name",$polja["polje_ime"]);
				$this->assign("kampanja_start",$polja["polje_start"]);
				$this->assign("kampanja_end",$polja["polje_end"]);
				$this->assign("kampanja_selected",$polja["polje_selected"]);
			$polja = $this->get_Cene($cenovnik_id);
				$this->assign("stavka_id",$polja["polje_id"]);
				$this->assign("stavka_name",$polja["polje_ime"]);
				$this->assign("stavka_artikl",$polja["polje_artikl"]);
				$this->assign("stavka_tip",$polja["polje_artikl_tip"]);
				$this->assign("stavka_boja",$polja["polje_artikl_boja"]);
				$this->assign("stavka_mera",$polja["polje_artikl_mera"]);
				$this->assign("stavka_jmere",$polja["polje_artikl_jmere"]);
				$this->assign("stavka_cena",$polja["polje_cena"]);
				
			$polja = $this->get_Paketi($cenovnik_id);
				$this->assign("pack_id",$polja["polje_id"]);
				$this->assign("pack_name",$polja["polje_ime"]);
				$this->assign("pack_cena",$polja["polje_cena"]);
				$this->assign("pack_start_date",$polja["polje_start_date"]);
				$this->assign("pack_end_date",$polja["polje_end_date"]);
				$this->assign("pack_sadrzaj",$polja["polje_sadrzaj"]);
				$this->assign("pack_sadrzaj_desc",$polja["polje_sadrzaj_desc"]);
				
			$polja = $this->get_TipoviUlaza();
				$this->assign("tip_ulaza_id",$polja["polje_id"]);
				$this->assign("tip_ulaza_name",$polja["polje_ime"]);
			
			$polja = $this->get_TipoviMaterijala();
				$this->assign("mattip_id",$polja["polje_id"]);
				$this->assign("mattip_name",$polja["polje_ime"]);
				$this->assign("mattip_itdt",array_fill(0,count($polja["polje_id"]),"1"));
			
			$this->assign("stavka_head_name","Naziv artikla");
			$this->assign("itdt_id","1");
			
			$polja = $this->get_HostingProviders();
				$this->assign("provider_id",$polja["polje_id"]);
				$this->assign("provider_name",$polja["polje_ime"]);
			$polja = $this->get_ProfiliTipovi();
				$this->assign("profil_tip_id",$polja["polje_id"]);
				$this->assign("profil_tip_name",$polja["polje_ime"]);
			$polja = $this->get_BaneriTipovi();
				$this->assign("baner_tip_id",$polja["polje_id"]);
				$this->assign("baner_tip_name",$polja["polje_ime"]);
				
			$polja = $this->get_UgovorNaciniPlacanja();
				$this->assign("np_id",$polja["polje_id"]);
				$this->assign("np_name",$polja["polje_ime"]);
				$this->assign("np_code",$polja["polje_code"]);
			
			/*$this->assign("act_id",array("0","1","2"));
			$this->assign("act_out",array("20.11.2007","18.10.2007","01.01.2006"));
			$this->assign("act_in",array("25.11.2007","20.10.2007","01.01.2006"));
			$this->assign("act_designer",array("Luka Veselinović","Voislav Jovanović","Marko Marinković"));
			$this->assign("act_designer_note",array("Oglas urađen","Materijal je neodgovarajući","Nema materijala"));
			$this->assign("act_editor",array("Žarko Popović","Žarko Popović","Slađana Popović"));
			$this->assign("act_napomena",array("","",""));*/
			
			$this->assign("itdt_tok",$this->parseTemplate("ugovori/novi/stavka_tok_item.tpl"));
			
			$this->assign("logo_pre",'/logo/');
			$this->assign("baner_pre",'/baner/');
			
			echo $this->parseTemplate("ugovori/novi/stavke.tpl");
		}else{
			echo "Nema{!}0";
		}
	}
	function newUgovorAddMaterijal(){
		$date = getFromInput("date");
		$polja = $this->get_TipoviUlaza();
			$this->assign("tu_id",$polja["polje_id"]);
			$this->assign("tu_name",$polja["polje_ime"]);
		$polja = $this->get_TipoviMaterijala();
			$this->assign("tm_id",$polja["polje_id"]);
			$this->assign("tm_name",$polja["polje_ime"]);
		$this->assign("date",$date);
		
		echo $this->parseTemplate("ugovori/materijal_add.tpl");
	}
	function newUgovorEditMaterijal(){
		$data = readValFromInput("data");
		$data = $this->VSON($data);
		
		$polja = $this->get_TipoviUlaza($data["tip_ulaza"]);
			$this->assign("tu_id",$polja["polje_id"]);
			$this->assign("tu_name",$polja["polje_ime"]);
			$this->assign("selected_tu",$polja["polje_selected"]);
		$polja = $this->get_TipoviMaterijala();
			$this->assign("tm_id",$polja["polje_id"]);
			$this->assign("tm_name",$polja["polje_ime"]);
			if(is_array($data["tip_materijala"])){
				//echo "yes";
				foreach ($polja["polje_id"] as $k=>$v){
					if (in_array($v,$data["tip_materijala"])) {
						$polja["polje_selected"][$k] = " checked";
					}else{
						$polja["polje_selected"][$k] = "";
					}
				}
				$this->assign("checked_tm",$polja["polje_selected"]);
			}
			
		$this->assign("date",$data["date"]);
		$this->assign("checked_upotrebljiv",$data["upotrebljiv"]>0?" checked":"");
		$this->assign("napomena",$data["napomena"]);
		$this->assign("edit","1");
		
		echo $this->parseTemplate("ugovori/materijal_add.tpl");
	}
	function newUgovorAddAction(){
		$polja = $this->get_RadniciByType(array(12,14,15));
			$this->assign("design_id",$polja["polje_id"]);
			$this->assign("design_ime",$polja["polje_ime"]);
			$this->assign("design_prezime",$polja["polje_prezime"]);
			$this->assign("design_selected",$polja["polje_selected"]);
		$polja = $this->get_RadniciByType(array(32),$this->getUserId());
			$this->assign("editor_id",$polja["polje_id"]);
			$this->assign("editor_ime",$polja["polje_ime"]);
			$this->assign("editor_prezime",$polja["polje_prezime"]);
			$this->assign("editor_selected",$polja["polje_selected"]);
		echo $this->parseTemplate("ugovori/action_add.tpl");
	}
	function newUgovorEditAction(){
		$data = readValFromInput("data");
		$data = $this->VSON($data);
		//print_rarray($data);
		
		$polja = $this->get_RadniciByType(array(12,14,15),$data["designer"]);
			$this->assign("design_id",$polja["polje_id"]);
			$this->assign("design_ime",$polja["polje_ime"]);
			$this->assign("design_prezime",$polja["polje_prezime"]);
			$this->assign("design_selected",$polja["polje_selected"]);
		$polja = $this->get_RadniciByType(array(32),$data["editor"]);
			$this->assign("editor_id",$polja["polje_id"]);
			$this->assign("editor_ime",$polja["polje_ime"]);
			$this->assign("editor_prezime",$polja["polje_prezime"]);
			$this->assign("editor_selected",$polja["polje_selected"]);
		$this->assign("edit","1");
		$this->assign("date_out",$data["date_out"]);
		$this->assign("date_in",$data["date_in"]);
		$this->assign("checked_done",$data["done"]>0?" checked":"");
		$this->assign("designer_note",$data["designer_note"]);
		$this->assign("napomena",$data["napomena"]);
		echo $this->parseTemplate("ugovori/action_add.tpl");
	}
	
	function browse(){
		
		$kword = readValFromInput("kword",true);
		$exact = getFromInput("exact"); $exact = strlen($exact)>0?true:false;
		
		$this->assign("kword",$kword);
		$this->assign("exact_checked",$exact?" checked":"");
		
		$skword = $exact?$kword:"%$kword%";
		
		$page = getFromInput("page");
		$page = $page>0?$page:1;
		
		
		$q = "SELECT * FROM ugovori ";
		if (strlen($kword)>0) {
			$q .= "WHERE 0 ";
			$samobrojevi = preg_match('/^\d+$/',$kword);
			$sql = "SELECT komitent_id "
				  ."FROM komitenti "
				  ."WHERE komitent_name LIKE '$skword' "
				  ."OR komitent_name1 LIKE '$skword'";
			if ($samobrojevi) {
				$sql .= " OR komitent_id=$kword";
			}
			
			$komitenti = $this->db->select1($sql);
			$komids	= array();
			if ($komitenti) {
				foreach ($komitenti as $k=>$v){
					$komids[$k] = $v[0];
				}
			}
			if(count($komids)){
				$q .= "OR (komitent=".implode(" OR komitent=",$komids).") ";
			}
			
			$q .= "OR (broj LIKE '$skword'";
			if ($samobrojevi) {
				$q .= " OR id=$kword";
			}
			$q .= ") ";
			$q .= "OR komitent_ziro LIKE '$skword' ";
		}
		//echo $q;
		$ukupno = $this->db->select1($q);
		if ($ukupno) {
			$ukupno = count($ukupno);
		}else{
			$ukupno = 0;
		}
		$this->assign("info","Ukupno: $ukupno");
		
		$numpages = bcdiv($ukupno,PAGE_LENGTH,0);
		if ($ukupno%PAGE_LENGTH) {
			$numpages++;
		}
		
		$pageoffset=4;
		$numlimit = $numpages>($pageoffset*2)+1?($pageoffset*2)+1:$numpages;
		$start = $page>$pageoffset?$page-$pageoffset:1;
		
		if($numpages>$pageoffset){
			$start = ($start+($pageoffset*2)+1)>$numpages?$numpages-(2*$pageoffset):$start;
		}else{
			$start=1;
		}
		
		//echo "$start - $numlimit - $page";
		
		for ($i=$start,$j=0; $j<$numlimit; $i++,$j++){
			$pages[$j] = $i;
			if ($i == ($page)) {
				$pages_current[$j] = " id=\"current\"";
			}else{
				$pages_current[$j] = "";
			}
		}
		$this->assign("numpages",$numpages);
		$this->assign("page",$pages);
		$this->assign("current_page",$pages_current);
		
		$start = ($page-1)*PAGE_LENGTH;
		$q .= "ORDER BY id DESC LIMIT $start,".PAGE_LENGTH;
		//echo $q;
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $row){
				$id[] = $row["id"];
				$broj[] = $row["broj"];
				$komitent[] = $row["komitent"].". ".$this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$row["komitent"]." LIMIT 1");
				$datum[] = datetime2str($row["datum"]);
			}
			$this->assign("id",$id);
			$this->assign("broj",$broj);
			$this->assign("komitent",$komitent);
			$this->assign("datum",$datum);
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		$this->assign("filter_form",$this->parseTemplate("ugovori/pretraga_forma.tpl"));
		echo $this->parseTemplate("ugovori/pregled.tpl");
	}
	function display(){
		require_once("ugovori.display.class.php");
		$ugodisplay = new ugovori_display(getFromInput("id"));
	}
	
	function CheckLogo(){
		$logo = readValFromInput("logo");
		$prefix = readValFromInput("pre");
		$ugoid = getFromInput("ugoid");
		
		/*$rgx = '/^\\/*'.str_replace("/","\\/",$prefix).'/i';
		if(preg_match($rgx,$logo)){
			$logo = preg_replace($rgx,"",$logo);
		}*/
		$q = "SELECT u.id, u.broj, u.komitent "
			."FROM ugovori u, ugovori_stavke us, ugovori_tok_realizacije utr, internet_data id "
			."WHERE u.id=us.ugovor_id "
			."AND us.stavka_id=utr.stavka "
			."AND utr.tok_id=id.id_tok "
			."AND (id.profil_logo='$logo' OR id.profil_logo='$prefix$logo') "
			."AND u.id!=$ugoid";
		$res = $this->db->getRow($q);
		if ($res === null) {
			$code = 0;
		}else{
			$komid = $res[2];
			$komitent = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=$komid LIMIT 1");
			$ugobroj = $res[1];
			$ugoid = $res[0];
			
			$code = 1;
			$msg = "Ugovor: $ugobroj, Komitent: $komid. $komitent";
		}
		echo "$code{!}$msg";
	}
	
	function save(){
		require_once("ugovori.save.class.php");
		$ugosave = new ugovori_save($_POST);
	}
	
	function deleteUgovor(){
		$id = getFromInput("id");
		if (intval($id)<1) {
			die("1{!}Nepoznat id ugovora.");
		}
		
		$code = 0;
		$msg = "Ugovor je obrisan.";
		/*
		TRUNCATE TABLE ugovori;
		TRUNCATE TABLE dopisi;
		TRUNCATE TABLE deklaracije;
		TRUNCATE TABLE ugovori_stavke;
		TRUNCATE TABLE ugovori_tok_realizacije;
		TRUNCATE TABLE tok_materijali;
		TRUNCATE TABLE ugovori_tok_actions;
		TRUNCATE TABLE internet_data;
		TRUNCATE TABLE tok_trajanje_periodi;
		TRUNCATE TABLE knjiga_data;
		TRUNCATE TABLE ugovori_plan_otplate;
		TRUNCATE TABLE ugovori_plan_rate;
		TRUNCATE TABLE ugovori_otplate;
		TRUNCATE TABLE ugovori_problem_fields;*/
		
		$queries[] = "DELETE FROM ugovori WHERE id=$id LIMIT 1";
		
		$stavke = $this->db->select2("SELECT stavka_id FROM ugovori_stavke WHERE ugovor_id=$id");
		if ($stavke !== false) {
			
			foreach ($stavke as $stavka){
				$stavkaid = $stavka["stavka_id"];
				$queries[] = "DELETE FROM ugovori_stavke WHERE stavka_id=$stavkaid LIMIT 1";
				
				$tok_realizacije = $this->db->select2("SELECT tok_id FROM ugovori_tok_realizacije WHERE stavka=$stavkaid");
				if($tok_realizacije !== false){
					
					foreach ($tok_realizacije as $tok){
						$tokid = $tok["tok_id"];
						$queries[] = "DELETE FROM ugovori_tok_realizacije WHERE tok_id=$tokid LIMIT 1";
						$queries[] = "DELETE FROM tok_materijali WHERE tok=$tokid LIMIT 1";
						$queries[] = "DELETE FROM ugovori_tok_actions WHERE tok=$tokid LIMIT 1";
						$queries[] = "DELETE FROM tok_trajanje_periodi WHERE id_tok=$tokid LIMIT 1";
						$queries[] = "DELETE FROM internet_data WHERE id_tok=$tokid LIMIT 1";
						$queries[] = "DELETE FROM knjiga_data WHERE id_tok=$tokid LIMIT 1";
					}
				}
			}
		}
		$queries[] = "DELETE FROM ugovori_plan_otplate WHERE ugovor_id=$id";
		$plan_otplate = $this->db->select2("SELECT plan_id FROM ugovori_plan_otplate WHERE ugovor_id=$id");
		if($plan_otplate !== false){
			foreach ($plan_otplate as $plan){
				$planid = $plan["plan_id"];
				$queries[] = "DELETE FROM ugovori_plan_rate WHERE rata_plan=$planid LIMIT 1";
			}
		}
		
		$queries[] = "DELETE FROM ugovori_otplate WHERE ugoid=$id";
		
		$queries = array_reverse($queries);
		foreach ($queries as $q){
			if (!$this->db->alterTable($q)) {
				$code = 1;
				$msg = mysql_error();
				break;
			}
		}
		require_once("log.change.class.php");
		$log = new log_change();
		$log->user = $this->getUserId();
		$log->time = time();
		$log->ip = $_SERVER['REMOTE_ADDR'];
		$log->state = 3;
		$log->table = "ugovori";
		$log->attr = "id";
		$log->value = $id;
		$log->write();
		
		echo "$code{!}$msg";
	}
	
	function importDeklaracijaKomitentData(){
		$id = getFromInput("id");
		$q = "SELECT komitent_name, komitent_adresa, komitent_matbr, komitent_vlasnik_name, komitent_vlasnik_jmbg "
			."FROM komitenti WHERE komitent_id=$id LIMIT 1";
		list($res) = $this->db->select2($q);
		
		$a = $this->adrese->getAll($res["komitent_adresa"]);
		$res["komitent_adresa"] = $a["ulica"]." ".$a["broj"].", ".$a["lokacija"]["mesto"]["ptt"]." ".$a["lokacija"]["mesto"]["name"];
		
		$out = "";
		foreach ($res as $k=>$v){
			$out .= "\n$k=$v";
		}
		if (strlen($out)) {
			$out = substr($out,1);
		}
		echo $out;
	}
	
	function planMakeTable(){
		
		$date		= getFromInput("date");
		$brrata 	= getFromInput("brrata");
		$bruto		= getFromInput("bruto");
		$korekcija	= getFromInput("korekcija");
		$porez		= getFromInput("porez");
		$neto		= getFromInput("neto");
		$avans		= getFromInput("avans");
		$np			= getFromInput("np");
		
		$bruto = strip_number_format($bruto);
		$korekcija = strip_number_format($korekcija);
		$porez = strip_number_format($porez);
		$neto = strip_number_format($neto);
		$avans = strip_number_format($avans);
		
		$date = explode(".",$date);
		$date = array(
			"day"	=> intval($date[0]),
			"month"	=> intval($date[1]),
			"year"	=> intval($date[2])
		);
		if ($date["month"]>11) {
			$nextMonth = $date["month"]-11;
			$nextYear = $date["year"]+1;
		}else{
			$nextMonth = $date["month"]+1;
			$nextYear = $date["year"];
		}
		//$thisMonthMaxDay = date("d",makeUnixTime(0,0,0,$nextMonth,1,$nextYear)-1);
		// prva rata start
		$date["month"] = $nextMonth;
		$date["year"] = $nextYear;
		/*if ($date["month"]>12) {
			$date["day"] = $date["day"] - $thisMonthMaxDay;
			$date["month"] += 1;
			
			if ($date["month"]>12) {
				$date["month"] -= 12;
				$date["year"] += 1;
			}
		}*/
		
		$brrata = $np==2?0:$brrata;

		$por_perc = round(100*$porez/($bruto-$porez),2);
		$por = bcdiv($por_perc*$bto,($por_perc+100),2);
		$iznos = $bruto-$avans;
		
		$u_nto = $u_bto = $u_por = 0;
		
		$avans = floatval($avans);
		$avans_neto = round($avans*100/(100+$por_perc),2);
		$avans_porez = round($avans_neto*$por_perc/100,2);
		$this->assign("avans_bruto",number_format($avans,2,",","."));
		$this->assign("avans_neto",number_format($avans_neto,2,",","."));
		$this->assign("avans_porez",number_format($avans_porez,2,",","."));
		
		$u_bto += $avans;
		$u_nto += $avans_neto;
		$u_por += $avans_porez;
		
		if ($brrata>0) {
			$plan_bto = round($iznos/$brrata,2);
			$plan_nto = round($plan_bto*100/(100+$por_perc),2);
			$plan_por = round($plan_nto*$por_perc/100,2);
			
			$u_bto += $plan_bto*$brrata;
			$u_por += $plan_por*$brrata;
			$u_nto += $plan_nto*$brrata;
			
			for ($i=0; $i<$brrata; $i++){
				$num[$i] = $i+1;
				
				$nd = $date["day"];
				$nm = $i>0?($date["month"] + 1):$date["month"];
				$ny = $date["year"];
				
				// sledeca godina
				if ($nm>12) {
					$nm = $nm-12;
					$ny++;
				}
				// poslednji dan
				$thisMonthMaxDay = intval(date("d",makeUnixTime(0,0,0,$nm+1,1,$ny)-1));
				if ($nd>$thisMonthMaxDay) {
					$nd = $thisMonthMaxDay;
				}
				$date["month"] = $nm;
				$date["year"] = $ny;
				
				$nd = $nd<10?"0".$nd:$nd;
				$nm = $nm<10?"0".$nm:$nm;
				
				$plan_date[$i] = "$nd.$nm.$ny";
				
				
				$plan_neto[$i] = number_format($plan_nto,2,",",".");
				$plan_bruto[$i] = number_format($plan_bto,2,",",".");
				$plan_porez[$i] = number_format($plan_por,2,",",".");
			}
		}
		$this->assign("num",$num);
		$this->assign("datum",$plan_date);
		$this->assign("plan_neto",$plan_neto);
		$this->assign("plan_bruto",$plan_bruto);
		$this->assign("plan_porez",$plan_porez);
		$this->assign("ukupno_neto",number_format($u_nto,2,",","."));
		$this->assign("ukupno_bruto",number_format($u_bto,2,",","."));
		$this->assign("ukupno_porez",number_format($u_por,2,",","."));
		echo $this->parseTemplate("ugovori/plan_otplate_table.tpl");
	}
	
	/**
	 * ALARMI
	 * 
	 */
	function alarms(){
		$today = date2int(date("d.m.Y"));
		$day1 = 60*60*24;
		$days15 = 15*$day1;
		
		$q_join = "SELECT u.komitent, u.broj, id.hosting_yp_start, id.hosting_yp_end "
				."FROM ugovori u, ugovori_stavke us, ugovori_tok_realizacije utr, internet_data id "
				."WHERE u.id=us.ugovor_id "
				."AND us.stavka_id=utr.stavka "
				."AND utr.tok_id=id.id_tok ";
		
		// HOSTING YP
		$q = $q_join
			."AND hosting_yp_end=".($today+$days15);
			
		echo $q;
		
		echo $this->parseTemplate("ugovori/alarms.tpl");
	}
	
	function searchUlazMat($ugo,$kom){
		
		$sm = new search_mat();
		
		$q1 = "SELECT uu.id, uu.br_ugovora, uu.komitent, uu.artikl, um.potpun "
			."FROM ugovori_ulaz uu, ugovori_ulaz_materijal um "
			."WHERE uu.materijal=1 AND uu.id=um.id";
		$q = "SELECT id, br_ugovora, komitent, artikl "
			."FROM ugovori_ulaz "
			."WHERE materijal=0";
		if($ugo){
			$search_kword = "ugovor: $ugo";
			$q1  .= " AND uu.br_ugovora like '$ugo%'";
			$q .= " AND br_ugovora like '$ugo%'";
		}
		if($kom){
			if($ugo)
				$search_kword .= ", ";
			$search_kword .= "komitent: $kom";
			$q1  .= " AND uu.komitent LIKE '%$kom%'";
			$q .= " AND komitent LIKE '%$kom%'";
		}
		$q .= " ORDER BY br_ugovora, komitent";
		$q1.= " ORDER BY uu.br_ugovora, uu.komitent";
		
		$ulazi = $this->db->select2($q);
		$ulazi1 = $this->db->select2($q1);
		
		// ugovori_ulaz, mat=0
		if($ulazi[0]){
			foreach ($ulazi as $ul){
				$id = $ul["id"];
				$ugo = $ul["br_ugovora"];
				$kom = $ul["komitent"];
				$art = $ul["artikl"];
				
				$um = new ulaz_materijal();
				$um->ugo = $ugo;
				$um->kom = $kom;
				$um->art = $art;
								
				$sm->ulazi[$id] = $um;
			}
		}
		// ugovori_ulaz_materijal, potpun=0
		if($ulazi1[0]){
			foreach ($ulazi1 as $ul){
				$id = $ul["id"];
				$ugo = $ul["br_ugovora"];
				$kom = $ul["komitent"];
				$art = $ul["artikl"];
				$potpun = $ul["potpun"];
				
				if(!array_key_exists($id,$sm->ulazi)){
					$um = new ulaz_materijal();
					$um->ugo = $ugo;
					$um->kom = $kom;
					$um->art = $art;
					$sm->ulazi[$id] = $um;
				}
				$sm->ulazi[$id]->potp[] = $potpun;
			}
		}
		foreach ($sm->ulazi as $k=>$ulaz){
			if(array_search("1",$ulaz->potp) === false){
				$ulaz_ids[] = $k;
				$ulaz_ugs[] = $ulaz->ugo;
				$ulaz_kms[] = $ulaz->kom;
				
				$artikl = $this->getArticles($ulaz->art);
				$ulaz_artikl[] = implode(" - ",$artikl);
				
				if(count($ulaz->potp)){
					$ulaz_pps[] = "<span style=\"float:right; display:block; background:red; color:white; padding:0px 2px; font-size:10px;\">nepotpun</span>";
				}else{
					$ulaz_pps[] = "";
				}
				
			}else{
				unset($sm->ulazi[$k]);
			}
			
		}
		$this->assign("search_length",$search_length);
		$this->assign("search_kword",$search_kword);
		$this->assign("list_num",$ulaz_ugs);
		$this->assign("list_item",$ulaz_kms);
		$this->assign("list_item_artikl",$ulaz_artikl);
		$this->assign("list_item_id",$ulaz_ids);
		$this->assign("list_item_potpun",$ulaz_pps);
		echo $this->parseTemplate("ugovori/search_list.tpl");
		/*echo '<pre>';
		print_r($sm);
		echo '</pre>';*/
		
		/*if($ulazi[0]){
			$search_length = count($ulazi)." ";
			foreach ($ulazi as $ulaz){
				$ulaz_ids[] = $ulaz["id"];
				$ulaz_ugs[] = $ulaz["br_ugovora"];
				$ulaz_kms[] = $ulaz["komitent"];
				
				if(isset($ulaz["potpun"]) && $ulaz["potpun"]==0){
					$ulaz_pps[] = "<span style=\"float:right; display:block; background:red; color:white; padding:0px 2px; font-size:10px;\">nepotpun</span>";
				}else{
					$ulaz_pps[] = "";
				}
				
				$artikl = $this->getArticles($ulaz["artikl"]);
				$ulaz_artikl[] = implode(" - ",$artikl);
			}
		}else{
			$search_length = "0 ";
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->");
		}
		$this->assign("search_length",$search_length);
		$this->assign("search_kword",$search_kword);
		$this->assign("list_num",$ulaz_ugs);
		$this->assign("list_item",$ulaz_kms);
		$this->assign("list_item_artikl",$ulaz_artikl);
		$this->assign("list_item_id",$ulaz_ids);
		$this->assign("list_item_potpun",$ulaz_pps);
		echo $this->parseTemplate("ugovori/search_list.tpl");*/
	}
	function ulazMatEdit($id,$kom){
		list($res) = $this->db->select2("SELECT br_ugovora, artikl FROM ugovori_ulaz WHERE id=$id");
		$br_ugovora = $res["br_ugovora"];
		$artikl = implode(" - ",$this->getArticles($res["artikl"]));
				
		$this->assign("br_ugovora",$br_ugovora);
		$this->assign("artikl",$artikl);
		$this->assign("komitent_name",$kom);
		$this->assign("ulaz_id",$id);
		echo $this->parseTemplate("ugovori/ulaz_mat_edit.tpl");
	}
	function ulazMatSave($id,$type,$potpun,$napomena,$update){
		$ok = true;
		
		$napomena = utf8RawUrlDecode($napomena);
		$napomena = utf8RawChrDecode($napomena);
		
		$date = time();
		$radnik = $_COOKIE["ypu"];
		$ip = $_SERVER['REMOTE_ADDR'];
		
		$q = "UPDATE ugovori_ulaz SET materijal=1 WHERE id=$id";
		if(!$this->db->alterTable($q)){
			$ok = false;
		}
		$q = "INSERT INTO ugovori_ulaz_materijal VALUES($id,$date,'$type',$potpun,$radnik,'$ip','$napomena')";
		
		if(!$this->db->alterTable($q)){
			$ok = false;
			$err = mysql_error();
		}
		if($ok){
			echo "Izmene su uspešno ažurirane";
		}else{
			echo "GREŠKA! Izmene nisu izvršene.\n$err";
		}
	}
	function utf8RawUrlDecode ($source) {
		$decodedStr = '';
		$pos = 0;
		$len = strlen ($source);
		while ($pos < $len) {
				$charAt = substr ($source, $pos, 1);
				if ($charAt == '%') {
					$pos++;
					$charAt = substr ($source, $pos, 1);
					if ($charAt == 'u') {
						// we got a unicode character
						$pos++;
						$unicodeHexVal = substr ($source, $pos, 4);
						$unicode = hexdec ($unicodeHexVal);
						$entity = "&#". $unicode . ';';
						$decodedStr .= utf8_encode ($entity);
						$pos += 4;
					}else {
						// we have an escaped ascii character
						$hexVal = substr ($source, $pos, 2);
						$decodedStr .= chr (hexdec ($hexVal));
						$pos += 2;
					}
				}else {
					$decodedStr .= $charAt;
					$pos++;
				}
		}
		return $decodedStr;
	}
	function utf8RawChrDecode($str){
		$mask = array(
			262 => "Ä†",
			263 => "Ä‡",
			268 => "ÄŚ",
			269 => "ÄŤ",
			352 => "Ĺ ",
			353 => "Ĺˇ",
			381 => "Ĺ˝",
			382 => "Ĺľ",
			272 => "Ä�",
			273 => "Ä‘"
		);
		foreach ($mask as $k=>$v){
			$str = str_replace("&#$k;",$v,$str);
		}
		return $str;
	}
	function getArticles($sifra){
		$tmp = explode(";",$sifra);
		$art_id		= $tmp[0];
		$art_tip	= $tmp[1];
		$art_boja	= $tmp[2];
		$art_mera	= $tmp[3];
		
		$return = array();
		
		// artikl
		if($art_id){
			$art_name = $this->db->getOne("SELECT art_name FROM artikli WHERE art_id=$art_id LIMIT 1");
			$return["artikl"] = $art_name;
		}
		// artikl tip
		if($art_tip){
			$art_tip_name = $this->db->getOne("SELECT arttip_name FROM artikli_tipovi WHERE arttip_id=$art_tip LIMIT 1");
			$return["tip"] = $art_tip_name;
		}
		// artikl boja
		if($art_boja){
			$art_boja_name = $this->db->getOne("SELECT art_boja_code FROM artikli_boje WHERE art_boja_id=$art_boja LIMIT 1");
			$return["boja"] = $art_boja_name;
		}
		// artikl mera
		if($art_mera){
			$art_mera_name = $this->db->getOne("SELECT unit_svalue FROM jedinice_mere WHERE unit_id=$art_mera LIMIT 1");
			$return["mera"] = $art_mera_name;
		}
		return $return;
	}
	function showVratiUgovor(){
		
		$id = getFromInput("id");
		$polja = $this->get_Radnici();
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
		
		$this->assign("ulaz_id",$id);
		
		echo $this->parseTemplate("ugovori/ulaz_vrati.tpl");
	}
	function vratiUgovor(){
		$komentar = readValFromInput("komentar");
		$radnik = getFromInput("radnik");
		$ulaz_id = getFromInput("ulaz_id");
		$datum = time();
		$q = "INSERT INTO ugovori_ulaz_vracen VALUES('',$ulaz_id,$radnik,$datum,1,'$komentar')";
		if($this->db->alterTable($q)){
			echo "Ugovor vraćen.";
		}else{
			echo mysql_error();
		}
	}
	function vratiUnesiUgovor(){
		$id = getFromInput("id");
		
		$q = "SELECT radnik, ulaz_id FROM ugovori_ulaz_vracen WHERE id=$id";
		list($radnik,$ulaz_id) = $this->db->getRow($q);
		$datum = time();
		
		$q = "INSERT INTO ugovori_ulaz_vracen VALUES('',$ulaz_id,$radnik,$datum,0,'')";
		if($this->db->alterTable($q)){
			echo "Ugovor je uspešno ponovo vraćen u firmu.";
		}else{
			echo mysql_error();
		}
	}
	
	/**
	 * ADMINISTRACIJA DOPISA
	 *
	 */
	
	function adminDopisTypes(){
		$dt = $this->get_DopisTipovi();
		//print_rarray($dt);
		foreach ($dt["polje_id"] as $k=>$dtid){
			$ids[$k] = $dtid;
			$names[$k] = $dt["polje_ime"][$k];
		}
		$this->assign("dt_id",$ids);
		$this->assign("dt_name",$names);
		
		echo $this->parseTemplate("ugovori/admin/dopis_types.tpl");
	}
	function saveDopisType(){
		$id = intval(getFromInput("id"));
		$name = readValFromInput("name");
		
		$code = 0;
		$msg = "Tip dopisa je sačuvan.";
		
		if ($id>0) {
			$q = "UPDATE dopisi_tipovi SET name='".prepForSQL($name)."' WHERE tip_dopisa_id=$id LIMIT 1";
		}else{
			$q = "INSERT INTO dopisi_tipovi(name) VALUES('".prepForSQL($name)."')";
		}
		if (!$this->db->alterTable($q)) {
			$code = 1;
			$msg = mysql_error();
		}
		
		echo "$code{!}$msg";
	}
	function deleteDopisType(){
		$id = getFromInput("id");
		
		$code = 0;
		$msg = "Tip dopisa je obrisan.";
		
		if ($id>0) {
			$q = "DELETE FROM dopisi_tipovi WHERE tip_dopisa_id=$id LIMIT 1";
			if(!$this->db->alterTable($q)){
				$code = 1;
				$msg = mysql_error();
			}
		}
		
		echo "$code{!}$msg";
	}
	
	function adminDopisIshod(){
		$dt = $this->get_DopisIshodi();
		foreach ($dt["polje_id"] as $k=>$dtid){
			$ids[$k] = $dtid;
			$names[$k] = $dt["polje_ime"][$k];
		}
		$this->assign("dt_id",$ids);
		$this->assign("dt_name",$names);
		
		echo $this->parseTemplate("ugovori/admin/dopis_ishodi.tpl");
	}
	function saveDopisIshod(){
		$id = intval(getFromInput("id"));
		$name = readValFromInput("name");
		
		$code = 0;
		$msg = "Ishod dopisa je sačuvan.";
		
		if ($id>0) {
			$q = "UPDATE dopisi_ishodi SET name='".prepForSQL($name)."' WHERE dopis_ishod_id=$id LIMIT 1";
		}else{
			$q = "INSERT INTO dopisi_ishodi(name) VALUES('".prepForSQL($name)."')";
		}
		
		if (!$this->db->alterTable($q)) {
			$code = 1;
			$msg = mysql_error();
		}
		
		echo "$code{!}$msg";
	}
	function deleteDopisIshod(){
		$id = getFromInput("id");
		
		$code = 0;
		$msg = "Ishod dopisa je obrisan.";
		
		if ($id>0) {
			$q = "DELETE FROM dopisi_ishodi WHERE dopis_ishod_id=$id LIMIT 1";
			if(!$this->db->alterTable($q)){
				$code = 1;
				$msg = mysql_error();
			}
		}
		
		echo "$code{!}$msg";
	}
	
	//-------------------------------------- GET FUNCTIONS ----------------------------
	function get_UgovorTipovi($tip=null){
		$ret = array();
		$q = "SELECT * FROM ugovori_tipovi ORDER BY name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["tip_id"];
				$ret["polje_ime"][$k] = $v["name"];
				if ($tip == $v["tip_id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_UgovorProblemi($probid=null){
		$ret = array();
		$q = "SELECT * FROM ugovori_problemi ORDER BY name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["problem_id"];
				$ret["polje_ime"][$k] = $v["name"];
				if ($probid == $v["problem_id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_StatusiIzrade($statid=null){
		$ret = array();
		$q = "SELECT * FROM ugovori_obnove_status ORDER BY name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["status_id"];
				$ret["polje_ime"][$k] = $v["name"];
				if ($statid == $v["status_id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}

	function get_TipoviUlaza($tipid=null){
		$ret = array();
		$q = "SELECT * FROM materijal_tip_ulaza ORDER BY tip_ulaz_name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["tip_ulaz_id"];
				$ret["polje_ime"][$k] = $v["tip_ulaz_name"];
				$ret["polje_opis"][$k] = $v["tip_ulaz_desc"];
				if($tipid==$v["tip_ulaz_id"]){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_TipoviMaterijala($tipid=null){
		$ret = array();
		$q = "SELECT * FROM materijal_tipovi ORDER BY mattip_name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["mattip_id"];
				$ret["polje_ime"][$k] = $v["mattip_name"];
				if($tipid==$v["mattip_id"]){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_DeklaracijaTipPoruke($tip=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM deklaracije_tipovi ORDER BY dekl_tip_name");
		if ($res!==false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["dekl_tip_id"];
				$ret["polje_ime"][$k] = $v["dekl_tip_name"];
				if($v["dekl_tip_id"] == $tip){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_DopisTipovi($tip=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM dopisi_tipovi ORDER BY name");
		if($res !== false){
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["tip_dopisa_id"];
				$ret["polje_ime"][$k] = $v["name"];
				if ($v["tip_dopisa_id"] == $tip) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_DopisIshodi($ishod=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM dopisi_ishodi ORDER BY name");
		if($res !== false){
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["dopis_ishod_id"];
				$ret["polje_ime"][$k] = $v["name"];
				if ($v["dopis_ishod_id"] == $ishod) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_RadniciByType($types=null,$radid=null,$akt=1){
		$q = "SELECT radnik_id, radnik_ime, radnik_prezime "
			."FROM radnici "
			."WHERE radnik_akt=$akt ";
			if($types !== null){
				$q .= " AND ";
				if(is_array($types)){
					$q .= "(";
					foreach ($types as $tpid){
						$q .= "radnik_tip_id=$tpid OR ";
					}
					$q = substr($q,0,strlen($q)-4).") ";
				}else {
					$q .= "radnik_tip_id=$types ";
				}
			}
		$q .= "ORDER BY radnik_ime, radnik_prezime";
		$res = $this->db->select2($q);
		$ret=array();
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["radnik_id"];
				$ret["polje_ime"][$k] = $v["radnik_ime"];
				$ret["polje_prezime"][$k] = $v["radnik_prezime"];
				if($radid == $v["radnik_id"]){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_HostingProviders($id=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM hosting_providers ORDER BY name");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["provider_id"];
				$ret["polje_ime"][$k] = $v["name"];
				$ret["polje_adresa"][$k] = $v["adresa"];
				$ret["polje_tel"][$k] = $v["tel"];
				$ret["polje_web"][$k] = $v["web"];
				if ($v["provider_id"] == $id) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_ProfiliTipovi($id=null){
		$res = $this->db->select2("SELECT * FROM profili_tipovi ORDER BY code");
		$ret = array();
		foreach ($res as $k=>$v){
			$ret["polje_id"][$k] = $v["id"];
			$ret["polje_ime"][$k] = $v["code"];
			$ret["polje_desc"][$k] = $v["desc"];
			if($id == $v["id"]){
				$ret["selected"][$k] = " selected";
			}else{
				$ret["selected"][$k] = "";
			}
		}
		return $ret;
	}
	function get_BaneriTipovi($id=null){
		$ret=array();
		$res = $this->db->select2("SELECT * FROM baneri_tipovi ORDER BY name");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["id"];
				$ret["polje_ime"][$k] = $v["name"];
				$ret["polje_desc"][$k] = $v["desc"];
				if ($id==$v["id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_UgovorNaciniPlacanja($id=null){
		$ret=array();
		$res = $this->db->select2("SELECT * FROM nacini_placanja ORDER BY np_sifra");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["np_id"];
				$ret["polje_ime"][$k] = $v["np_name"];
				$ret["polje_code"][$k] = $v["np_sifra"];
				if ($id==$v["np_id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_LokacijeTipovi($tip=null){
		$ret = array("polje_id"=>null,"polje_ime"=>null,"polje_selected"=>null);
		foreach ($this->lok_types as $k=>$v){
			$key = count($ret["polje_id"]);
			$ret["polje_id"][$key] = $k;
			$ret["polje_ime"][$key] = $v;
			if (intval($tip)==$k) {
				$ret["polje_selected"][$key] = " selected";
			}else{
				$ret["polje_selected"][$key] = "";
			}
		}
		return $ret;
	}
	function get_Porezi($pid=null){
		$res = $this->db->select2("SELECT * FROM porezi ORDER BY porez_name");
		$ret = array();
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["porez_id"];
				$ret["polje_ime"][$k] = $v["porez_name"];
				$ret["polje_perc"][$k] = $v["porez_percent"];
				if ($pid == $v["porez_id"]) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	
	/**
	 * Preuzima zbir popusta sa stavki ugovora
	 * gde je kolicina stavke veca od 0
	 *
	 * @param id $id_ugovora
	 * @return float
	 */
	function getUgovorPopust($ugoid){
		$ret = (float) $this->db->getOne("SELECT SUM(popust) FROM ugovori_stavke WHERE kolicina>0 AND ugovor_id=$ugoid");
		return $ret;
	}
}
class search_mat{
	var $ulazi=array();
}
class ulaz_materijal{
	var $ugo;
	var $kom;
	var $art;
	var $potp=array();
}
?>